package com.chenyun.rpc.feign.config;

import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.chenyun.common.constants.AuthConstant;
import com.chenyun.common.constants.SaTokenConstant;
import com.chenyun.common.context.ServletContext;
import com.chenyun.common.context.UserContextHolder;
import com.chenyun.common.utils.StringUtils;
import com.chenyun.common.vo.SessionUser;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * sa-token在feign中加入id-token请求头
 * @author: Lonni
 * @date: 2022/11/7 0007 11:40
 */
@Slf4j
public class SatokenFeignRequestInterceptor implements RequestInterceptor, Ordered {

    public SatokenFeignRequestInterceptor(){
        log.info("SatokenFeignRequestInterceptor......>");
    }


    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = ServletContext.getRequest();
        log.info("SatokenFeignRequestInterceptor,feign请求拦截器执行......>");

        log.info("增加idtoken头");
        // 为 Feign 的 RCP调用 添加请求头Id-Token
        requestTemplate.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
        //增加token请求头
        log.info("增加feign调用标识");
        if (request.getHeader(SaTokenConstant.FEIGN_CLIENT_KEY)==null) {
            requestTemplate.header(SaTokenConstant.FEIGN_CLIENT_KEY, "true");
        }
        //将当前的用户id和租户id设置
        try {
            String tokenValueNotCut = StpUtil.getTokenValueNotCut();
            if (StringUtils.isNotBlank(tokenValueNotCut)){
                //加入到feign头部中
                log.info("增加JWT_TOKEN_HEADER头");
                requestTemplate.header(AuthConstant.JWT_TOKEN_HEADER, tokenValueNotCut);
                SessionUser loginUser = UserContextHolder.getUser();
                requestTemplate.header(SaTokenConstant.FEIGN_UID_KEY, loginUser.getUserId());
                requestTemplate.header(SaTokenConstant.FEIGN_TID_KEY, loginUser.getClientId());
            }
        }catch (Exception exception){
            log.debug("没有token,不加入");
        }
    }

    @Override
    public int getOrder() {
        return 11;
    }
}



